import _ from 'lodash';
import { startLoading, endLoading } from './loading';

export default function request(config: any = {}) {
  return new Promise((resolve, reject) => {
    startLoading();
    const _header: any = {};
    if (uni.getStorageSync('token') && config && config.headers) {
      _header['Authorization'] = 'Bearer ' + uni.getStorageSync('token');
    }
    uni.request({
      url:
        config.url && _.includes(config.url, 'http') ? config.url : `${import.meta.env.VITE_VUE_BASE_URL}${config.url}`,
      header: {
        ...config.header,
        ..._header
      },
      method: config.method || 'GET',
      data: config.data || {},
      success: (response: any) => {
        endLoading();
        const res = response.data;

        if (!res.code || !_.isNumber(res.code)) {
          return resolve(res);
        }
        if (res.code !== 200) {
          uni.showToast({
            title: res.msg || res.message || 'Error',
            duration: 3000
          });
        } else {
          return resolve(res);
        }
      },
      fail: (error: any) => {
        endLoading();
        if (error.message === 'Network Error') {
          uni.showToast({
            title: '访问网络不稳定，请稍后再试',
            duration: 3000
          });
          return reject(error);
        }
        if (error.message.includes('timeout')) {
          uni.showToast({
            title: '连接服务器超时，请稍后再试',
            duration: 3000
          });
          return reject(error);
        }
        uni.showToast({
          title: error.message,
          duration: 3000
        });
        return reject(error);
      }
    });
  });
}
